import json
import time
from collections import deque
import threading

class AudioDataManager:
    """
    音频数据管理器，用于接收、存储和处理来自音频处理器的数据
    """
    def __init__(self, max_history=1000):
        """
        初始化音频数据管理器
        
        Parameters:
        max_history: 最大历史数据存储数量
        """
        # 数据存储
        self.waveform_history = deque(maxlen=max_history)
        self.features_history = deque(maxlen=max_history)
        self.beat_history = deque(maxlen=max_history)
        
        # 实时数据
        self.current_waveform = None
        self.current_features = None
        self.current_beat = False
        
        # 统计信息
        self.total_beats = 0
        self.start_time = time.time()
        self.bpm = 0.0  # 每分钟节拍数
        
        # 锁机制确保线程安全
        self.lock = threading.Lock()
        
    def update_data(self, waveform_data, features):
        """
        更新音频数据
        
        Parameters:
        waveform_data: 波形数据
        features: 音频特征字典
        """
        with self.lock:
            # 更新波形数据
            self.current_waveform = waveform_data
            self.waveform_history.append(waveform_data.copy() if waveform_data is not None else None)
            
            # 更新特征数据
            self.current_features = features.copy() if features is not None else None
            self.features_history.append(features.copy() if features is not None else None)
            
            # 检查是否有节拍
            if features and features.get('is_beat', False):
                self.current_beat = True
                self.beat_history.append({
                    'timestamp': features.get('timestamp', time.time()),
                    'features': features.copy()
                })
                self.total_beats += 1
                
                # 计算BPM（每分钟节拍数）
                self._calculate_bpm()
            else:
                self.current_beat = False
    
    def _calculate_bpm(self):
        """
        计算BPM（每分钟节拍数）
        """
        if len(self.beat_history) >= 2:
            # 获取最近10个节拍计算BPM
            recent_beats = list(self.beat_history)[-10:]
            if len(recent_beats) >= 2:
                time_diff = recent_beats[-1]['timestamp'] - recent_beats[0]['timestamp']
                if time_diff > 0:
                    self.bpm = (len(recent_beats) - 1) * 60 / time_diff
    
    def get_current_data(self):
        """
        获取当前音频数据
        
        Returns:
        dict: 包含当前波形、特征和节拍信息的字典
        """
        with self.lock:
            return {
                'waveform': self.current_waveform,
                'features': self.current_features,
                'is_beat': self.current_beat,
                'bpm': self.bpm,
                'total_beats': self.total_beats
            }
    
    def get_history_data(self, count=100):
        """
        获取历史数据
        
        Parameters:
        count: 获取的历史数据数量
        
        Returns:
        dict: 包含历史波形、特征和节拍信息的字典
        """
        with self.lock:
            # 获取最近count个历史数据
            waveform_data = list(self.waveform_history)[-count:] if self.waveform_history else []
            features_data = list(self.features_history)[-count:] if self.features_history else []
            beat_data = list(self.beat_history)[-count:] if self.beat_history else []
            
            return {
                'waveform_history': waveform_data,
                'features_history': features_data,
                'beat_history': beat_data,
                'bpm': self.bpm,
                'total_beats': self.total_beats
            }
    
    def get_statistics(self):
        """
        获取统计信息
        
        Returns:
        dict: 包含统计数据的字典
        """
        with self.lock:
            duration = time.time() - self.start_time
            return {
                'total_beats': self.total_beats,
                'duration': duration,
                'bpm': self.bpm,
                'beats_per_second': self.total_beats / duration if duration > 0 else 0
            }
    
    def reset(self):
        """
        重置数据管理器
        """
        with self.lock:
            self.waveform_history.clear()
            self.features_history.clear()
            self.beat_history.clear()
            self.current_waveform = None
            self.current_features = None
            self.current_beat = False
            self.total_beats = 0
            self.start_time = time.time()
            self.bpm = 0.0
    
    def to_json(self, data=None):
        """
        将数据转换为JSON格式
        
        Parameters:
        data: 要转换的数据，如果为None则转换当前数据
        
        Returns:
        str: JSON格式的字符串
        """
        if data is None:
            data = self.get_current_data()
            
        # 处理不能直接序列化的数据
        def serialize(obj):
            if isinstance(obj, dict):
                result = {}
                for key, value in obj.items():
                    if isinstance(value, np.ndarray):
                        result[key] = value.tolist()
                    else:
                        result[key] = value
                return result
            return obj
        
        return json.dumps(serialize(data), default=str, ensure_ascii=False, indent=2)

# 全局数据管理器实例
audio_data_manager = AudioDataManager()

def data_callback(waveform_data, features):
    """
    数据回调函数，用于接收来自音频处理器的数据
    
    Parameters:
    waveform_data: 波形数据
    features: 音频特征字典
    """
    # 添加调试信息，但只在检测到节拍时输出
    if features and features.get('is_beat', False):
        print(f"接收到音频特征数据 - 音量: {features.get('amplitude_rms', 0):.2f}, "
              f"频率: {features.get('dominant_frequency', 0):.0f}Hz, "
              f"节拍: {features.get('is_beat', False)}")
    
    # 将数据传递给数据管理器
    audio_data_manager.update_data(waveform_data, features)

def get_audio_data_manager():
    """
    获取全局音频数据管理器实例
    
    Returns:
    AudioDataManager: 音频数据管理器实例
    """
    return audio_data_manager